/**
 * 创建上下文菜单
 * @param param - 鼠标事件和保存回调
 */
export function useContextMenu({
  mouseEvent,
  id,
  items,
}: {
  mouseEvent: MouseEvent;
  /** menu的div的id */
  id: string;
  items: Array<{
    /** 按钮文本 */
    text: string;
    /** 回调函数 */
    callback: () => void;
  }>;
}): HTMLDivElement {
  // 如果已经有右键菜单存在，应该先移除
  const _menu = document.getElementById(id);
  _menu && document.body.removeChild(_menu);
  // 创建右键菜单
  const menu = document.createElement('div');
  menu.setAttribute('id', id);
  menu.style.left = `${mouseEvent.clientX}px`;
  menu.style.top = `${mouseEvent.clientY}px`;

  // 创建菜单项的通用函数
  const createMenuItem = (text: string, callback: () => void): HTMLElement => {
    const item = document.createElement('div');
    item.textContent = text;
    item.addEventListener('click', callback);
    return item;
  };

  items.forEach(({ text, callback }) => {
    menu.appendChild(createMenuItem(text, callback));
  });
  // 菜单位置修正
  const menuRect = menu.getBoundingClientRect();
  const { clientWidth, clientHeight } = document.documentElement;

  let left = mouseEvent.clientX;
  let top = mouseEvent.clientY;

  // 检查是否会超出右边界
  if (left + menuRect.width > clientWidth) {
    left = Math.max(0, clientWidth - menuRect.width);
  }

  // 检查是否会超出下边界(90%阈值)
  const bottomThreshold = clientHeight * 0.9;
  if (top + menuRect.height > bottomThreshold) {
    top = Math.max(0, bottomThreshold - menuRect.height);
  }

  menu.style.left = `${left}px`;
  menu.style.top = `${top}px`;
  document.body.appendChild(menu);
  return menu;
}
